package com.bw.ivideoproject.home

import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.bw.ivideoproject.R
import com.bw.ivideoproject.databinding.ActivityDetailBinding
import com.bw.ivideoproject.entity.SimpleVideoEntity
import com.bw.ivideoproject.home.detailFragment.CommentFragment
import com.bw.ivideoproject.home.detailFragment.DescriptionFragment
import com.bw.ivideoproject.wight.BitmapUtils
import com.bw.ivideoproject.wight.DanMuBottomDialog
import com.bw.ivideoproject.wight.MyCacheStuffer
import com.bw.lib_mvvm.BaseActivity
import com.google.android.material.tabs.TabLayout
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import kotlin.random.Random

class DetailActivity : BaseActivity<ActivityDetailBinding>() {

    private lateinit var video:SimpleVideoEntity
    private lateinit var descriptionFragment:DescriptionFragment
    private lateinit var commentFragment:CommentFragment

    override fun initView() {
        init(intent)
        binding.tabHomeDetailType.addTab(binding.tabHomeDetailType.newTab().setText("简介"))
        binding.tabHomeDetailType.addTab(binding.tabHomeDetailType.newTab().setText("评论"))
        initDanmuk()
    }

    override fun initData() {
        binding.back.setOnClickListener {
            finish()
        }

        binding.gsyHomeDetail.fullscreenButton.setOnClickListener {
            binding.gsyHomeDetail.startWindowFullscreen(this@DetailActivity,false,true)
        }

        binding.tabHomeDetailType.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                when(tab?.text){
                    "简介"->{
                        replaceFragment(descriptionFragment)
                    }
                    "评论"->{
                        replaceFragment(commentFragment)
                    }
                }
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })

        binding.switchHomeDetailBulletscreen.setOnCheckedChangeListener{ bottomView,isCheck ->
            if(isCheck){
                val defaultDanmakParser = getDefaultDanmakParser()
                binding.dvHomeDetail.prepare(defaultDanmakParser,dmContext)
                binding.dvHomeDetail.resume()
            }else{
                binding.dvHomeDetail.stop()
            }
        }
        binding.tvHomeDetailDanmu.setOnClickListener {
            val bottomDialog = DanMuBottomDialog(this@DetailActivity)
            bottomDialog.show()

            bottomDialog.setOnClickListener(object : DanMuBottomDialog.OnClickListener{
                override fun danmuCompleted(content: String) {
                    addDanmaku(false,content)
                }
            })

        }
    }

    private lateinit var dmContext:DanmakuContext
    private val mCntentColorBg = arrayOf("#0099ff", "#b2d15c", "#b9b9f1", "#f46c77")

    private fun initDanmuk(){
        val maxLinesPair:HashMap<Int,Int> = HashMap(16)
        maxLinesPair[BaseDanmaku.TYPE_SCROLL_RL] = 8
        val overlappingEnablePair:HashMap<Int,Boolean> = HashMap(16)
        overlappingEnablePair[BaseDanmaku.TYPE_SCROLL_RL] = true
        overlappingEnablePair[BaseDanmaku.TYPE_FIX_TOP] = true

        dmContext = DanmakuContext.create()
        dmContext.setDuplicateMergingEnabled(false)
            .setScrollSpeedFactor(1.2f)
            .setScaleTextSize(1.2f)
            .setCacheStuffer(MyCacheStuffer(this),mBackgroundCacheStuffer)
            .setMaximumLines(maxLinesPair)
            .preventOverlapping(overlappingEnablePair)

        if(binding.dvHomeDetail != null){
            val defaultDanmakParser = getDefaultDanmakParser()

            binding.dvHomeDetail.setCallback(object :DrawHandler.Callback{
                override fun prepared() {
                    binding.dvHomeDetail.start()
                }
                override fun updateTimer(timer: DanmakuTimer?) {
                }
                override fun danmakuShown(danmaku: BaseDanmaku?) {
                }
                override fun drawingFinished() {
                }
            })
            binding.dvHomeDetail.prepare(defaultDanmakParser,dmContext)
            binding.dvHomeDetail.enableDanmakuDrawingCache(true)
        }
    }

    private val mBackgroundCacheStuffer: BaseCacheStuffer.Proxy =
        object : BaseCacheStuffer.Proxy() {
            override fun prepareDrawing(danmaku: BaseDanmaku, fromWorkerThread: Boolean) {
                // 根据你的条件检查是否需要需要更新弹幕
            }

            override fun releaseResource(danmaku: BaseDanmaku) {
                //清理相应的数据
                danmaku.tag = null
            }
        }

    private fun getDefaultDanmakParser(): BaseDanmakuParser? {
        return object : BaseDanmakuParser() {
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        }
    }

    override fun bindLayout(): Int {
        return R.layout.activity_detail
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)

        init(intent)
    }

    private fun init(intent: Intent?){
        video = intent?.getSerializableExtra("video") as SimpleVideoEntity
        binding.tvNormalTitleBar.text = video.title
        binding.gsyHomeDetail.setUp(video.videopath,false,null)
        binding.gsyHomeDetail.backButton.visibility = View.GONE
        IjkPlayerManager.setLogLevel(IjkMediaPlayer.IJK_LOG_SILENT)
        binding.gsyHomeDetail.startButton.performClick()
        binding.gsyHomeDetail.isShowFullAnimation=true

        descriptionFragment = DescriptionFragment()
        commentFragment = CommentFragment()
        val bundle = Bundle().apply {
            this.putSerializable("video",video)
        }
        descriptionFragment.arguments = bundle
        commentFragment.arguments = bundle
        replaceFragment(descriptionFragment)

    }

    override fun onDestroy() {
        super.onDestroy()
        binding.gsyHomeDetail.release()
    }

    fun replaceFragment(fragment: Fragment){
        supportFragmentManager.beginTransaction().replace(R.id.fl_home_detail_content,fragment).commitAllowingStateLoss()
    }

    private fun addDanmaku(isLive:Boolean,content:String){
        val danmaku:BaseDanmaku = dmContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)

        if(danmaku == null || binding.dvHomeDetail == null){
            return
        }

        var showBitmap = BitmapFactory.decodeResource(resources,R.mipmap.home_danmu)
        showBitmap = BitmapUtils.getShowPicture(showBitmap)
        val map:MutableMap<String,Any> = HashMap(16)
        map["content"] = content
        map["bitmap"] = showBitmap
        val randomNum = Random.nextInt(mCntentColorBg.size)
        map["color"] = mCntentColorBg[randomNum]
        danmaku.tag = map
        danmaku.textSize = 0f
        danmaku.padding = 10
        danmaku.text = ""
        danmaku.priority = 1
        danmaku.isLive = false
        danmaku.time = binding.dvHomeDetail.currentTime
        danmaku.textColor = Color.WHITE
        danmaku.textShadowColor = 0
        binding.dvHomeDetail.addDanmaku(danmaku)
    }
}